package com.terren.spider.util.common;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONWriter;

import com.terren.spider.entity.common.SentimentTag;
import com.terren.spider.entity.config.SysConfig;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NLPClient {
	private static OkHttpClient client;

    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(3600, TimeUnit.SECONDS)
                .readTimeout(3600, TimeUnit.SECONDS)
                .build();
    }
	 
	private static String similarURL = SysConfig.SIMILAR_URL;
	private static String sentimentTagURL = SysConfig.SENTIMENT_TAG_URL;

	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	public static final MediaType TEXT = MediaType.parse("text/plain; charset=utf-8");

	public static Map<String, Integer> countSimilar(Map<String, String> articles) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		OutputStream zipper = new GZIPOutputStream(bos);
		Writer w = new OutputStreamWriter(zipper);
		JSONWriter jw = new JSONWriter(w);

		// create json object
		jw.array();
		for (Map.Entry<String, String> entry : articles.entrySet()) {
			jw.object();

			jw.key("id");
			jw.value(entry.getKey());

			jw.key("text");
			jw.value(entry.getValue());

			jw.endObject();
		}
		jw.endArray();

		w.flush();
		w.close();

		RequestBody body = RequestBody.create(JSON, bos.toByteArray());

		Request request = new Request.Builder().url(similarURL).header("Content-Encoding", "gzip").post(body).build();

		Response response = null;

		try {
			 response = client.newCall(request).execute();
			 if (!response.isSuccessful()) {
				  throw new Exception("文本比较失败:" + response.body().string());
			 }
			 JSONArray arr = new JSONArray(response.body().string());
			 HashMap<String, Integer> result = new HashMap<String, Integer>();
			 for (int i = 0; i < arr.length(); i++) {
				  JSONObject o = arr.getJSONObject(i);
				  result.put(o.getString("id"), o.getInt("count"));
			 }
			 return result;
		} finally {
			 response.close();
		}
	}

	public static SentimentTag getSentimentTag(String text) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		OutputStream zipper = new GZIPOutputStream(bos);
		Writer w = new OutputStreamWriter(zipper);
		w.write(text);
		w.close();

		RequestBody body = RequestBody.create(TEXT, bos.toByteArray());
		Request request = new Request.Builder().url(sentimentTagURL).header("Content-Encoding", "gzip").post(body)
				.build();

		Response response = client.newCall(request).execute();
		if (!response.isSuccessful()) {
			throw new Exception("情感分析失败:" + response.body().string());
		}

		JSONObject obj = new JSONObject(response.body().string());
		String sentiment = obj.getString("sentiment");
		String tag = obj.getString("prop");

		return new SentimentTag(sentiment, tag);
	}
}
